import { defineStore } from "pinia";
import { useTabStore } from "../..";
import { returnType } from "@/utils";
import { LAYOUT_SCROLL_EL_ID } from '@soybeanjs/vue-materials';

const useState = () => ({
  scrollElId: LAYOUT_SCROLL_EL_ID,
  /** 主体内容全屏 */
  contentFull: ref(false),
  /** 禁用主体内容的水平方向的滚动 */
  disableMainXScroll: ref(false),
  /** 重载页面(控制页面的显示) */
  reloadFlag: ref(true),
  /** 重载页面(当前刷新组件的名称) */
  reloadComponentName: ref(""),
  /** 项目配置的抽屉可见状态 */
  settingDrawerVisible: ref(false),
  /** 侧边栏折叠状态 */
  siderCollapse: ref(false),
  /** vertical-mix模式下 侧边栏的固定状态 */
  mixSiderFixed: ref(false),
});

const stateType = returnType(useState);
type State = typeof stateType;

const useAction = (state: State) => ({
  /** 刷新页面 */
  reloadPage: async () => {
    const { activeTab } = useTabStore();
    state.reloadComponentName.value = activeTab.meta.componentName || "";

    state.reloadFlag.value = false;
    window.$loadingBar?.start();

    await nextTick();
    state.reloadFlag.value = true;
    state.reloadComponentName.value = "";
    setTimeout(() => {
      document.documentElement.scrollTo({ left: 0, top: 0 });
      window.$loadingBar?.finish();
    }, 100);
  },
  /** 打开设置抽屉 */
  openSettingDrawer: () => {
    state.settingDrawerVisible.value = true;
  },
  /** 关闭设置抽屉 */
  closeSettingDrawer: () => {
    state.settingDrawerVisible.value = false;
  },
  /** 切换抽屉可见状态 */
  toggleSettingDrawerVisible() {
    state.settingDrawerVisible.value = !state.settingDrawerVisible.value;
  },
  /** 设置侧边栏折叠状态 */
  setSiderCollapse: (collapse: boolean) => {
    state.siderCollapse.value = collapse;
  },
  /** 折叠/展开 侧边栏折叠状态 */
  toggleSiderCollapse: () => {
    state.siderCollapse.value = !state.siderCollapse.value;
  },
  /** 设置 vertical-mix模式下 侧边栏的固定状态 */
  setMixSiderIsFixed: (isFixed: boolean) => {
    state.mixSiderFixed.value = isFixed;
  },
  /** 设置 vertical-mix模式下 侧边栏的固定状态 */
  toggleMixSiderFixed: () => {
    state.mixSiderFixed.value = !state.mixSiderFixed.value;
  },
  /** 设置主体是否禁用滚动 */
  setDisableMainXScroll: (disable: boolean) => {
    state.disableMainXScroll.value = disable;
  },
  /** 设置主题内容全屏 */
  setContentFull: (flag: boolean) => {
    state.contentFull.value = flag;
  },
});

export const useAppStore = defineStore("app-store", () => {
  const state = useState();
  const action = useAction(state);
  return { ...state, ...action };
});
